package photobox.manage

import grails.transaction.Transactional
import photobox.account.ApplyForPhotographer
import photobox.account.Notice
import photobox.account.User
import photobox.utils.HQLUtils

@Transactional
class ApplyForPhotographerService {

    def list(searchParam, pageParam, sortParam) {
        def hql = ""
        hql += " from ApplyForPhotographer A where 1=1 "
        def params = [:]
        if (searchParam.id) {
            hql += " and " + HQLUtils.whereCondition("A.id", searchParam.id.opt, "id")
            params.id = searchParam.id.data
        }
        if (searchParam.userId) {
            hql += " and " + HQLUtils.whereCondition("A.userId", searchParam.userId.opt, "userId")
            params.userId = searchParam.user.data
        }
        if (searchParam.content) {
            hql += " and " + HQLUtils.whereCondition("A.content", searchParam.content.opt, "content")
            params.content = searchParam.content.data
        }
        if (searchParam.dateCreated) {
            hql += " and " + HQLUtils.whereCondition("A.dateCreated", searchParam.dateCreated.opt, "dateCreated")
            params.dateCreated = searchParam.dateCreated.data
        }
        if (searchParam.lastUpdated) {
            hql += " and " + HQLUtils.whereCondition("A.lastUpdated", searchParam.lastUpdated.opt, "lastUpdated")
            params.lastUpdated = searchParam.lastUpdated.data
        }
        if (searchParam.agreement) {
            hql += " and " + HQLUtils.whereCondition("A.agreement", searchParam.agreement.opt, "agreement")
            params.agreement = searchParam.agreement.data
        }

        def sortHql = ""
        if (sortParam.sort) {
            sortHql = " order by A.${sortParam.sort} ${sortParam.order} "
        }
        def results = ApplyForPhotographer.executeQuery("select distinct A " + hql + sortHql, params,
                [max: pageParam.pageSize, offset: pageParam.offset])
        def count = ApplyForPhotographer.executeQuery("select count(distinct A.id) " + hql, params)
        return [rs:results, total:count[0]]
    }
    def saveApply(session){
        def applyForPhotographer = new ApplyForPhotographer()
        def user = User.get(session.userId)
        applyForPhotographer.user  =  user
        applyForPhotographer.content = "sdasd"
        applyForPhotographer.agreement = applyForPhotographer.AGREEMENT_NULL

        if(!applyForPhotographer.save()){
            println(applyForPhotographer.errors)
        }
    }
    def saveNotice(applyForPhotographer,message){
        def notice = new Notice()
        notice.user=applyForPhotographer.user
        notice.message= message
        notice.isRead = 0
        notice.readTime = new Date()
        if(!notice.save()){
            println(notice.errors)
        }

    }
}
